package com.hitsoyauce.mail.common;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.hitsoyauce.common.BASE64;
import com.hitsoyauce.common.CalendarHelper;
import com.hitsoyauce.common.PreferenceHelper;
import com.hitsoyauce.common.PropertiesReader;
import com.hitsoyauce.common.Util;

public class MailHelper {
	
	private static String filePath;
	
	public static Session getSession(boolean isDebug) {
		Properties props = new Properties();
		
		if (isDebug) {
			props.setProperty("mail.debug", "true");
		}
		
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.transport.protocol", "smtp");
		
		Session session = Session.getInstance(props);
		session.setDebug(isDebug);
		
		return session;
	}

	/**
	 * 获取邮件内容
	 * @return
	 * @throws IOException 
	 */
	public static String getMailText() throws IOException {
		String result = getDefaultText();
		BufferedReader br = null;
		
		try {
			br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "gbk"));
			
			String lineText = "";
			String content = "";
			int splitLineCount  = 1;
			int contentLine = 0;
			
			while(true) {
				lineText = br.readLine();
				
				if (lineText == null) {
					result = result.replace("{" + splitLineCount + "}", content);
					break;
				}
				
				if(lineText.equals("")) continue;
				
				if (lineText.startsWith("---") && lineText.endsWith("---")) {
					result = result.replace("{" + splitLineCount + "}", content);
					content = "";
					contentLine = 0;
					splitLineCount ++;
					continue;
				}
				
				content += ++ contentLine + ". " +  lineText;
				
				content = addSuffix(lineText, content);
			}
			
		} catch (IOException o) {
			o.printStackTrace();
			throw o;
		}
		
		return result;
	}

	/**
	 * 添加后缀
	 * @param lineText
	 * @param content
	 * @return
	 */
	private static String addSuffix(String lineText, String content) {
		if (Character.isDigit(lineText.charAt(lineText.length() - 1))) {
			content += "小时";
		}
			
		if (!lineText.endsWith("。")) {
			content += "。";
		}
		
		content += "\n";
		return content;
	}
	
	/**
	 * 获取缺省的邮件内容（即除了日报的正文）
	 * @return
	 */
	private static String getDefaultText() {
		BufferedReader br = null;
		String result = "";
		
		try {
			br = new BufferedReader(new InputStreamReader(MailHelper.class.getResourceAsStream("/defaultMailText.txt"), "utf-8"));
			String lineText = "";
			while(true) {
				lineText = br.readLine();
				if (lineText != null || "".equals(lineText)) {
					result += lineText + "\n";
				} else {
					break;
				}
			}
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		result = result.replace("{0}", getName());
		result = result.replace("{4}", getName());
		result = result.replace("{5}", getDepartment());
		result = result.replace("{6}", getMailAddress());
		result = result.replace("{7}", getPhone());
		
		return result;
	}

	
	/**
	 * 获取Message Object
	 * @return
	 * @throws IOException 
	 * @throws MessagingException 
	 */
	public static Message getMessage() throws IOException, MessagingException {
		Message message = new MimeMessage(getSession(Boolean.parseBoolean(PropertiesReader.getProperty("isDebug"))));
		try {
			message.setText(MailHelper.getMailText());
			message.setRecipients(RecipientType.TO, new Address[] {new InternetAddress(PreferenceHelper.getPreference("mailTo"))});
			message.setSubject(getSubject());
			message.setFrom(new InternetAddress(getMailAddress()));
			
			message.setSentDate(new Date());
		} catch (MessagingException ex) {
			ex.printStackTrace();
			throw ex;
		}
		
		return message;
	}
	
	//发送邮件
	public static void sendMessage() throws MessagingException, IOException {
		Transport trans = null;
		try {
			trans = getSession(Boolean.parseBoolean(PropertiesReader.getProperty("isDebug"))).getTransport();
			String host = PropertiesReader.getProperty("smtpServer");
			int port = Integer.parseInt(PropertiesReader.getProperty("smtpPort"));
			
			String user = PreferenceHelper.getPreference("username");
			String password = BASE64.decryptBASE64(PreferenceHelper.getPreference("password"));
			
			trans.connect(host, port, user, password);
			trans.sendMessage(getMessage(), new Address[] {new InternetAddress(PreferenceHelper.getPreference("mailTo"))});
			
			trans.close();
			
		} catch (MessagingException e) {
			trans = null;
			e.printStackTrace();
			throw e;
		}
	}
	
	/**
	 * 设置文件路径
	 * @param path
	 */
	public static void setFilePath(String path) {
		filePath = path;
		
		if (!getDefaultPath().equals(filePath)) {
			PreferenceHelper.setPreference("textPath", filePath);
		}
	}
	
	/**
	 * 获取文件路径
	 * @param path
	 */
	public static String getFilePath() {
		return filePath;
	}
	
	/**
	 * 获取缺省路径，即配置过的路径
	 * @return
	 */
	public static String getDefaultPath() {
		return PreferenceHelper.getPreference("textPath");
	}
	
	/**
	 * 获取缺省的主题（技术部  刘培军  2012/10/29 工作日报）
	 * @return
	 */
	private static String getSubject() {
		return getDepartment() + " " + getName() + " " + getDate() + " " + "工作日报";
	}
	
	/**
	 * 姓名
	 * @return
	 */
	private static String getName() {
		return PreferenceHelper.getPreference("name");
	}
	
	/**
	 * 部门
	 * @return
	 */
	private static String getDepartment() {
		return Util.isNull(PropertiesReader.getProperty("department")) ?  "技术部" : PropertiesReader.getProperty("department");
	}
	
	/**
	 * 日报日期
	 * @return
	 */
	private static String getDate() {
		return Util.isNull(PropertiesReader.getProperty("date")) ?  CalendarHelper.getNowYMD() : PropertiesReader.getProperty("date");
	}
	/**
	 * mailFrom
	 * @return
	 */
	private static String getMailAddress() {
		return  PreferenceHelper.getPreference("mailFrom");
	}
	
	/**
	 * 电话
	 * @return
	 */
	private static String getPhone() {
		return Util.isNull(PreferenceHelper.getPreference("phone")) ?  "025-82230530" : PreferenceHelper.getPreference("phone");
	}
	
}
